package com.szh.mysobproject.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.szh.mysobproject.databinding.ShareListItemBinding
import com.szh.mysobproject.model.UserShare
import com.szh.mysobproject.util.DateHelper
import com.szh.mysobproject.util.setFixOnClickListener


class ShareListAdapter(private val adapterDelegate: AdapterDelegate) :
    PagingDataAdapter<UserShare.Content, ShareListAdapter.ShareListViewHolder>(ShareDiffCallback()) {

    class ShareDiffCallback : DiffUtil.ItemCallback<UserShare.Content>() {
        override fun areItemsTheSame(
            oldItem: UserShare.Content,
            newItem: UserShare.Content
        ): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(
            oldItem: UserShare.Content,
            newItem: UserShare.Content
        ): Boolean {
            return oldItem == newItem
        }

    }

    inner class ShareListViewHolder(val binding: ShareListItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onViewAttachedToWindow(holder: ShareListViewHolder) {
        super.onViewAttachedToWindow(holder)
        adapterDelegate.onViewAttachedToWindow(holder)
    }

    override fun onBindViewHolder(holder: ShareListViewHolder, position: Int) {
        val item = getItem(position) ?: return
        val itemView = holder.itemView
        val binding = holder.binding
        val tvShareTitle = binding.tvShareTitle
        val tvDesc = binding.tvDesc
        itemView.setFixOnClickListener {
            adapterDelegate.onItemClick(it,position)
        }
        tvShareTitle.text= item.title
        tvDesc.text = DateHelper.getFriendlyTimeSpanByNow("${item.createTime}:00")
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShareListViewHolder {
        val binding =
            ShareListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ShareListViewHolder(binding)
    }
}